﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddCrmLiveSale.aspx.cs"
    Inherits="ZX.WebApp.Crm.MeetingArrange.AddCrmLiveSale" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <link rel="stylesheet" type="text/css" href="../../scripts/yui_2.9.0/build/container/assets/skins/sam/container.css" />
    <link rel="stylesheet" type="text/css" href="../../scripts/yui_2.9.0/build/button/assets/skins/sam/button.css" />
    <link rel="stylesheet" type="text/css" href="../../scripts/yui_2.9.0/build/layout/assets/skins/sam/layout.css" />
    <link rel="stylesheet" type="text/css" href="../../scripts/yui_2.9.0/build/resize/assets/skins/sam/resize.css" />
    <link rel="stylesheet" type="text/css" href="../../Scripts/yui_2.9.0/build/datatable/assets/skins/sam/datatable.css" />
    <link href="../../Styles/base.css" rel="stylesheet" type="text/css" />
    <link href="../../Styles/default/calendar.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/jquery-1.6.min.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.json-2.2.js" type="text/javascript"></script>
    <script src="../../Scripts/Jquery.form.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.calendar.js" type="text/javascript"></script>
    <script src="../../Scripts/CombinButton.js" type="text/javascript"></script>
    <script src="../../Scripts/extend.validate.js" type="text/javascript"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/calendar/calendar-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/element/element-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/datasource/datasource-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/json/json-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/connection/connection-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/get/get-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/dragdrop/dragdrop-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/datatable/datatable-min.js"></script>
    <script type="text/javascript" src="../../Scripts/yui_2.9.0/build/paginator/paginator-min.js"></script>
    <script type="text/javascript" src="../../scripts/yui_2.9.0/build/layout/layout-min.js"></script>
    <script type="text/javascript" src="../../scripts/yui_2.9.0/build/button/button-min.js"></script>
    <script type="text/javascript" src="../../scripts/yui_2.9.0/build/container/container-min.js"></script>
    <script type="text/javascript" src="../../scripts/yui_2.9.0/build/resize/resize-min.js"></script>
    <script type="text/javascript" src="../../scripts/yui_2.9.0/build/event-delegate/event-delegate-min.js"></script>
    <link href="../../Styles/extendTable.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        /* Table样式 */
         body{font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small; background: #eeeeee;}
        /* Table样式 */
       
        textarea                                                                    
        {
            height:100px;
        }
        label
        {
            font-size:14px;
            text-align:right;
            width:200px;
        }
        .btn 
        { 
            border-right: #7b9ebd 1px solid; 
            padding-right: 2px; 
            border-top: #7b9ebd 1px solid; 
            padding-left: 2px; 
            font-size: 12px; 
            FILTER: progid:DXImageTransform.Microsoft.Gradient(GradientType=0,  StartColorStr=#ffffff,  EndColorStr=#cecfde); 
            border-left: #7b9ebd 1px solid; 
            cursor: hand; 
            color: black; 
            height:24px;
            padding-top: 2px; 
            border-bottom: #7b9ebd 1px solid; 
        } 

   </style>
</head>
<body class="yui-skin-sam">
    <form id="form1" runat="server" name="myform">
    <div id="toolbar" style="margin: 2px;">
        <button type="button" id="btnSave" name="btnSave">
            保存退出</button>
        <button type="reset" id="btnFull" name="btnFull">
            重置</button>
        <button type="button" id="btnClose" name="btnClose">
            退出</button>
    </div>
    <div class="fieldForm" id="fieldForm">
        <table class="tableContent">
            <tr>
                <td>
                    <fieldset>
                        <legend>&nbsp;新增现场销售管理 </legend>
                        <table class="tableContent">
                            <tr>
                                <td width="100">
                                    &nbsp;客户选择：<span style="color: Red">*</span>
                                </td>
                                <td>
                                    <input type="hidden" id="CustomId" runat="server" name="CustomId" />
                                    <input id="txtCustomId" runat="server" name="txtCustomId" type="text" readonly="readonly"
                                        style="width: 150px;" />
                                    <button id="btnCustomId" name="Y" type="button" class="btn">
                                        选择</button>
                                    <span class="span_font">请选择对的客户名称</span>
                                </td>
                                <td width="100">
                                    &nbsp;客户编码
                                </td>
                                <td width="308">
                                    <asp:TextBox ID="Code" runat="server" Enabled="false" Width="150px" BackColor="Beige"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td width="100">
                                    &nbsp;客户来源：
                                </td>
                                <td>
                                    <asp:TextBox ID="CustomerFrom" Width="150" runat="server" ReadOnly="true" BackColor="Beige"></asp:TextBox>
                                </td>
                                <td width="100">
                                    &nbsp;信息专员：
                                </td>
                                <td>
                                    <asp:TextBox ID="InformationPro" Width="150" runat="server" ReadOnly="true" BackColor="Beige"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td width="100">
                                    &nbsp;行销顾问：
                                </td>
                                <td>
                                    <asp:TextBox ID="SaleGw" Width="150" runat="server" ReadOnly="true" BackColor="Beige"></asp:TextBox>
                                </td>
                                <td width="100">
                                    &nbsp;一推讲师：
                                </td>
                                <td>
                                    <asp:TextBox ID="FirstTeacher" Width="150" runat="server" ReadOnly="true" BackColor="Beige"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td width="100">
                                    &nbsp;客户经理：
                                </td>
                                <td>
                                    <asp:TextBox ID="CMName" Width="150" runat="server" ReadOnly="true" BackColor="Beige"></asp:TextBox>
                                </td>
                                <td width="100">
                                    &nbsp;课中服务人：
                                </td>
                                <td>
                                    <asp:TextBox ID="MiddleService" Width="150" runat="server" ReadOnly="true" BackColor="Beige"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td width="100">
                                    &nbsp;签单人：
                                </td>
                                <td>
                                    <input type="hidden" id="Memember" runat="server" />
                                    <input type="text" id="txtMemember" runat="server" dtype="Z" disabled="disabled"
                                        style="background: Beige; width: 150" />
                                    <button id="btnMemember" name="R" type="button" runat="server" class="btnCheck">
                                        选择</button>
                                    <%--   <asp:TextBox ID="SignSaler" Width="150" runat="server"  BackColor="Beige"></asp:TextBox>--%>
                                </td>
                                <td width="100">
                                    &nbsp;所属分公司：
                                </td>
                                <td>
                                    <asp:TextBox ID="BelongDepart" Width="150" runat="server" ReadOnly="true" BackColor="Beige"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td width="100">
                                    &nbsp;产品包：
                                </td>
                                <td>
                                    <asp:DropDownList ID="ddlProductPack" runat="server" Width="158" AppendDataBoundItems="true">
                                        <asp:ListItem Value=""> </asp:ListItem>
                                    </asp:DropDownList>
                                </td>
                                <td width="100">
                                    &nbsp;收款方式：
                                </td>
                                <td>
                                    <asp:DropDownList ID="ddlPayType" runat="server" Width="158">
                                    </asp:DropDownList>
                                </td>
                            </tr>
                            <tr>
                                <td width="100">
                                    &nbsp;POS号：
                                </td>
                                <td>
                                    <asp:TextBox ID="POSNum" Width="150" runat="server"></asp:TextBox>
                                </td>
                                <td width="100">
                                    &nbsp;合同号：
                                </td>
                                <td>
                                    <asp:TextBox ID="PactNum" Width="150" MaxLength="30" runat="server"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td width="100">
                                    &nbsp;是否开发票：<span style="color: Red">*</span>
                                </td>
                                <td>
                                    <asp:DropDownList ID="ddlIsInvoice" runat="server" Width="158">
                                        <asp:ListItem Value="2">--请选择--</asp:ListItem>
                                        <asp:ListItem Value="1">是</asp:ListItem>
                                        <asp:ListItem Value="0">否</asp:ListItem>
                                    </asp:DropDownList>
                                </td>
                                <td width="100">
                                    &nbsp;发票号：
                                </td>
                                <td>
                                    <asp:TextBox ID="InvoiceNum" onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"
                                        Width="150" runat="server"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td width="100">
                                    &nbsp;收据号：
                                </td>
                                <td>
                                    <asp:TextBox ID="ReceiptNum" Width="150" onkeyup="this.value=this.value.replace(/\D/g,'')"
                                        onafterpaste="this.value=this.value.replace(/\D/g,'')" runat="server"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td width="100">
                                    &nbsp;备注：
                                </td>
                                <td colspan="3">
                                    <asp:TextBox ID="Explain" TextMode="MultiLine" title="最多可输入500个汉字" Width="80%" runat="server"></asp:TextBox>
                                </td>
                            </tr>
                            <tr>
                                <td width="100">
                                    &nbsp;再来一条：
                                </td>
                                <td colspan="3">
                                    <input id="onceMore" name="onceMore" type="checkbox" /><span class="span_font"> 选中后，提交可以继续在本页面添加</span>
                                </td>
                            </tr>
                        </table>
                    </fieldset>
                </td>
            </tr>
        </table>
        <div class="extendDiv">
            <div id="con_two_1">
                <h3>
                    产品信息
                    <button type="button" id="btnNew1" name="btnNew1">
                        新增</button>
                    <button type="button" id="btnDelete1" name="btnDelete1">
                        删除</button>
                </h3>
                <div id="con_1">
                </div>
            </div>
            <div class="TotalMoneyDiv">
                
                <span>总折扣率</span>
                <input type="text" runat="server" id="TotalRebate" name="TotalRebate" onkeyup="if(isNaN(value))execCommand('undo')"
                    onchange="TotalRebateChange(this.value)" onafterpaste="if(isNaN(value))execCommand('undo')"
                    style="width: 70px;" />
                 
                <span style="color: Red;">应收总金额</span>
                <input type="text" runat="server" id="TotalMoney" name="TotalMoney" readonly="readonly"
                    onkeyup="if(isNaN(value))execCommand('undo')" onafterpaste="if(isNaN(value))execCommand('undo')"
                    style="width: 70px;" />
                <span style="color: Red;">已收总金额</span>
                <input type="text" runat="server" id="ShouldMoney" name="ShouldMoney" readonly="readonly"
                    style="width: 70px;" />
            </div>
        </div>
    </div>
    <div id="dialog1" class="yui-pe-content">
        <div class="hd">
            信息选择</div>
        <div class="bd">
            <iframe id="EditUIWindow1" frameborder="0" src="" style="width: 100%; height: 100%;
                margin: 0px; padding: 0px;"></iframe>
        </div>
    </div>
    <asp:HiddenField ID="ID" runat="server" />
    <asp:HiddenField ID="AddUser" runat="server" />
    <asp:HiddenField ID="AddTime" runat="server" />
    <asp:HiddenField ID="CrmDeliverMajorID" runat="server" />
    </form>
    <form id="form2" action="../../Extend/AjaxData/DataSave.aspx">
    <textarea style="display: none" id="jsonDataContent" rows="2" cols="2" name="jsonDataContent"></textarea>
    </form>
</body>
<script type="text/javascript">
   // function document.oncontextmenu() { event.returnValue = false; } //屏蔽鼠标右键
     var Url = "../../Extend/AjaxData/CustomOperating.aspx";
    var flag = "0",entity = "",uname="",
        view="",OperStatus="",
        WorkFlowId="",
        WorkTaskId="",
        OperatorInstanceId="",
        WorkflowInsId="",
        WorkTaskInsId="",
        Title="",
        Descript = "";
    var CrmProduct =[<%=ListCrmProduct %>],  CrmOrderProdcut=[<%=ListOrderProduct %>],
        CrmListUnitId=[<%=ListUnitId %>];
    var getTsid;
    var myDataSource1, mDataTable1;
    var btnNews1 = "", btnDeletes1 = "";
    var action = "<% =DataAction %>", condition = "", tempProduct = [<%=StrProduct %>], tempProductPack = [<%=StrProductPack %>], StrProductId = "<%=StrProductId %>";
    <asp:Literal ID="EditTemplate" runat="server"></asp:Literal>
    (function () {
        var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event;
        Event.onDOMReady(function () {
            var layout = new YAHOO.widget.Layout({
                units: [
                { position: 'top', height: 35, body: 'toolbar', gutter: '1 1 1 1', scroll: null, zIndex: 2 },
                { position: 'center', body: 'fieldForm', gutter: '0 1 1 1', scroll: true }
            ]
            });
            layout.render();
        });
    })();
    YAHOO.example.init = function () {
        function onButtonClick(p_oEvent) {
            switch (this.get("id")) {
                case "btnSave":
                    Save();
                    break;
                case "btnFull":
                    clearForm();
                    break;
                case "btnClose":
                    WinClose();
                    break;
                case "btnNew1":
                    handleAdd();
                    break;
                case "btnDelete1":
                    handleDelete();
                    break;
                default:
                    break;
            }
        }
        YAHOO.util.Event.onContentReady("toolbar", function () {
            var btnSave = new YAHOO.widget.Button("btnSave");
            btnSave.on("click", onButtonClick);
            var btnFull = new YAHOO.widget.Button("btnFull");
            btnFull.on("click", onButtonClick);
            var btnClose = new YAHOO.widget.Button("btnClose");
            btnClose.on("click", onButtonClick);

        });
        YAHOO.util.Event.onContentReady("con_two_1", function () {
        btnNews1 = new YAHOO.widget.Button("btnNew1");
        btnNews1.on("click", onButtonClick);
        btnDeletes1 = new YAHOO.widget.Button("btnDelete1");
        btnDeletes1.on("click", onButtonClick);
       
//        if (flag == "1" || flag == "3" || flag == "4") {
//            btnNews1._button.style.display = "none";
//            $("#btnNew1").attr('disabled', "true");
//            btnDeletes1._button.style.display = "none";
//            $("#btnDelete1").attr('disabled', "true");
//            return;
//        }
    });
    } ();

    YAHOO.namespace("example.container");
    YAHOO.util.Event.onDOMReady(function () {
        var handleSubmit = function () {   
            var editwindow = document.getElementById("EditUIWindow1");
            if (editwindow) {
                editwindow.contentWindow.ChooseInfo(); 
                LoadCustomerData();
            }
            YAHOO.example.container.dialog1.hide();
        };

        var handleCancel = function () {
            this.cancel();
        };
        var handleSuccess = function (o) {
            var response = o.responseText;
            response = response.split("<!")[0];
            document.getElementById("resp").innerHTML = response;
        };
        var handleFailure = function (o) {
            alert("Submission failed: " + o.status);
        };
        YAHOO.example.container.dialog1 = new YAHOO.widget.Dialog("dialog1",
					            { width: "650px",
					                height: "480px",
					                fixedcenter: true,
					                visible: false,
					                draggable: true,
					                close: true,
					                autofillheight: "body",
					                constraintoviewport: true,
					                buttons: [{ text: "确定", handler: handleSubmit, isDefault: true },
								            { text: "取消", handler: handleCancel}]
					            });
        YAHOO.example.container.dialog1.callback = { success: handleSuccess, failure: handleFailure };
        YAHOO.example.container.dialog1.render();
        //拖动大小
        var resize = new YAHOO.util.Resize("dialog1", {
            handles: ["br"],
            autoRatio: false,
            minWidth: 650,
            minHeight: 450,
            status: false
        });
        resize.on("startResize", function (args) {
            if (this.cfg.getProperty("constraintoviewport")) {
                var D = YAHOO.util.Dom;
                var clientRegion = D.getClientRegion();
                var elRegion = D.getRegion(this.element);
                resize.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
                resize.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
            } else {
                resize.set("maxWidth", null);
                resize.set("maxHeight", null);
            }
        }, YAHOO.example.container.dialog1, true);
        resize.on("resize", function (args) {
            var panelHeight = args.height;
            this.cfg.setProperty("height", panelHeight + "px");
        }, YAHOO.example.container.dialog1, true);
    });

 
      /* 对应的方法和ID*/
    var _fn, _id;
    function ShowDialog(fn, id,src) {
        _fn = fn;
        _id = id;
        document.getElementById("EditUIWindow1").src = src;
        YAHOO.example.container.dialog1.show();
    }
    /* 对应的方法和ID*/
    var _fn, _id;
    function ShowDialog1(fn, id,src) {
        _fn = fn;
        _id = id;
        document.getElementById("EditUIWindow1").src = src;
        YAHOO.example.container.dialog1.show();
    }
    //选择客户编码显示客户信息
    var LoadCustomerData = function () {  
        var vCId = "CustomerID='"+ document.getElementById("CustomId").value+"'";
        YAHOO.util.Connect.asyncRequest('GET', "../../Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=V_CrmDeliverMajorProductLayout&customCondition=" + vCId + "", //条件 
        {success: function (res) {
            try {
                var str = res.responseText;
                var arr = [];
                var obj = eval(str);
                $("#Code").val(obj[0].Code);
                $("#txtCustomId").val(obj[0].CustomerName);
                $("#CustomerFrom").val(obj[0].originName);
                $("#InformationPro").val(obj[0].AddUserName);
                $("#FirstTeacher").val(obj[0].LectorName);
                $("#SaleGw").val(obj[0].SaleadviserName);
                $("#CMName").val(obj[0].CustomerMgrName); 
                $("#MiddleService").val(obj[0].ClassServerName);
                $("#CrmDeliverMajorID").val(obj[0].ID);
                //$("#SignSaler").val(obj[0].SureName);
                $("#BelongDepart").val(obj[0].OrderofDeptName);
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
    });
}


var format1 = function (elCell, oRecord, oColumn, sData) {
 
        var str1 = [];
        var id = "id" + Math.random();
        str1.push("<option value='00'> </option>");
        if (flag == "1"  || flag == "3"  ) {
            str1.push("<select id='" + id + "' disabled='disabled' name='Caption' style='width:99%;'>");
        } else {
            str1.push("<select id='" + id + "' onchange='ChangeEvent1(this);' name='Caption' style='width:99%;'>");
        }
        str1.push("<option value='00'> </option>");
        for (var i = 0; i < CrmProduct.length; i++) {
            if (CrmProduct[i].Caption == sData) {
                str1.push("<option value='" + CrmProduct[i].Caption + "' selected>" + CrmProduct[i].Caption + "</option>");
            } else {
                str1.push("<option value='" + CrmProduct[i].Caption + "'>" + CrmProduct[i].Caption + "</option>");
            }
        }
        str1.push("</select>");
        elCell.innerHTML = str1.join("");
  
}
var format2 = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Code' style='width:95%; background: #e7eaf4;'>";
}
var format3 = function (elCell, oRecord, oColumn, sData) {
    if (sData == null || sData == "") {
        elCell.innerHTML = "<input type=\"text\" value=\"\" disabled='disabled' name='PhraseText' style='width:95%; background: #e7eaf4;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='PhraseText' style='width:95%; background: #e7eaf4;'>";
    }
}
var format4 = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Money' style='width:95%; background: #e7eaf4;'>";
}
var format5 = function (elCell, oRecord, oColumn, sData) {
    if (flag == "1" || flag == "3"  || flag == "4") {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Rebate' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' name='Rebate' onblur='ChangeEvent1(this);' style='width:95%;'>";
    }
}
var format6 = function (elCell, oRecord, oColumn, sData) {
    if (flag == "1" || flag == "3" || flag == "4") {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Amount' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' name='Amount' onchange='ChangeEvent1(this);' style='width:95%;'>";
    }
}
var format7 = function (elCell, oRecord, oColumn, sData) {
    
        var str1 = [];
        var id = "id" + Math.random();
        str1.push("<option value='00'> </option>");
       
            str1.push("<select id='" + id + "' onchange='ChangeEvent1(this);' name='UnitId' style='width:98%;'>");
      
        str1.push("<option value='00'> </option>");
        for (var i = 0; i < CrmListUnitId.length; i++) {
            if (CrmListUnitId[i].PhraseID == sData) {
                str1.push("<option value='" + CrmListUnitId[i].PhraseID + "' selected>" + CrmListUnitId[i].PhraseText + "</option>");
            } else {
                str1.push("<option value='" + CrmListUnitId[i].PhraseID + "'>" + CrmListUnitId[i].PhraseText + "</option>");
            }
        }
        str1.push("</select>");
        elCell.innerHTML = str1.join("");
    
}
var format8 = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='RebateMoney' style='width:95%; background: #e7eaf4;'>";
}
var format9 = function (elCell, oRecord, oColumn, sData) {
    if (flag == "1" || flag == "3" ||  flag == "4") {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='AccountReceivable' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' name='AccountReceivable' onchange='ChangeEvent1(this);' style='width:95%;'>";
    }
}
var format10 = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='TypeId' style='width:95%; background: #e7eaf4;'>";
}
var format11 = function (elCell, oRecord, oColumn, sData) {
    if (sData == null || sData == "") {
        elCell.innerHTML = "<input type=\"text\" value=\"\" disabled='disabled' name='UnitType' style='width:95%; background: #e7eaf4;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='UnitType' style='width:95%; background: #e7eaf4;'>";
    }
}
var format12 = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='ProductId' style='width:95%; background: #e7eaf4;'>";
}

var formatResign = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
    elCell.innerHTML = "<input type=\"text\" value=\"\" name='ResignMoney' onchange='ChangeEvent1(this);' style='width:95%;'>"; }else{
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" name='ResignMoney' onchange='ChangeEvent1(this);' style='width:95%;'>"; 
    }

}
var formatBeResign = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
        elCell.innerHTML = "<input type=\"text\" value=\"\" disabled='disabled' name='BeResignMoney' style='width:95%; background: #e7eaf4;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='BeResignMoney' style='width:95%; background: #e7eaf4;'>";
    }
}

YAHOO.util.Event.addListener(window, "load", function () {    
    BindData();
    hideCol();
});
var BindData = function () {
    YAHOO.example.InlineCellEditing = function () {     
        var myColumnDefs1 = [
            { key: "ID", label: "ID", resizeable: true },
            { key: "ProductId", label: "ProductId", resizeable: true, formatter: format12 },
            { key: "TypeId", label: "产品类型", resizeable: true, formatter: format10, width: 80 },
            { key: "Caption", label: "产品名称", resizeable: true, formatter: format1, width: 250 },
            { key: "Code", label: "产品编码", resizeable: true, formatter: format2 },
            { key: "PhraseText", label: "产品类型", resizeable: true, formatter: format3, width: 80 },
            { key: "Money", label: "定价", resizeable: true, formatter: format4,width:80 },
            { key: "UnitId", label: "计量单位", resizeable: true, formatter: format7, width: 50 },
            { key: "UnitType", label: "计量单位", resizeable: true, formatter: format11,width:50 },
            { key: "Amount", label: "数量", resizeable: true, formatter: format6,width:50,
                editor: new YAHOO.widget.TextboxCellEditor({validator:YAHOO.widget.DataTable.validateNumber})},
            { key: "Rebate", label: "折扣率(%)", resizeable: true, formatter: format5,width:50,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })},
            { key: "RebateMoney", label: "折扣金额", resizeable: true, formatter: format8,width:80 },
            { key: "AccountReceivable", label: "应收金额", resizeable: true, formatter: format9,width:80,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })},
            { key: "ResignMoney", label: "已收金额", resizeable: true,width:80, formatter: formatResign ,width:80,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })},
            { key: "BeResignMoney", label: "待收金额", resizeable: true,width:80, formatter: formatBeResign }
            ];
        myDataSource1 = new YAHOO.util.DataSource([{ ID: "", ProductId: "", Code: "", TypeId: "", UnitType: "", Caption: "",
            Money: "", Rebate: "", Amount: "", UnitId: "", UnitType: "", RebateMoney: "",
            ResignMoney: "", BeResignMoney: "", AccountReceivable: ""
        }]);
        myDataSource1.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        myDataSource1.responseSchema = {
            fields: ["ID", "ProductId", "Code", "TypeId", "PhraseText", "Caption", "Money", "Rebate", "Amount",
                     "UnitId", "UnitType", "RebateMoney", "ResignMoney", "BeResignMoney", "AccountReceivable"]
        };
        var myDataTable1 = new YAHOO.widget.ScrollingDataTable("con_1",
            myColumnDefs1, myDataSource1, { width: "99.8%", height:"100%", selectionMode: "single" });
        mDataTable1 = myDataTable1;
        var i1 = 1,
            bReverseSorted1 = false;
        var trackReverseSorts1 = function (oArg) {
            bReverseSorted1 = (oArg.dir === YAHOO.widget.DataTable.CLASS_DESC);
        };
        var onCellClick = function (e) {
            var ctrl = event.srcElement || e;
            if (ctrl.nodeName == "DIV") {
                
            }
        }
        var onEventSaveCellEditor = function (oArgs) {
            setValue1(oArgs.editor._oColumn.key, oArgs.newData);
        }
        myDataTable1.subscribe("rowMouseoverEvent", myDataTable1.onEventHighlightRow);
        myDataTable1.subscribe("rowMouseoutEvent", myDataTable1.onEventUnhighlightRow);
        myDataTable1.subscribe("rowClickEvent", myDataTable1.onEventSelectRow);  //mousedown
        myDataTable1.subscribe("cellClickEvent", myDataTable1.onEventShowCellEditor);
        myDataTable1.subscribe("editorSaveEvent", onEventSaveCellEditor);
        myDataTable1.subscribe("cellClickEvent", onCellClick);
        myDataTable1.subscribe("checkboxClickEvent", function (oArgs) {
            var elCheckbox = oArgs.target;
            var oRecord = this.getRecord(elCheckbox);
            oRecord.setData("iSun_Selected", elCheckbox.checked);
        });
        GetFormValue();
        return {
            ds: myDataSource1,
            dt: myDataTable1
        };
    } ();
}
//隐藏/栏位
function hideCol() {
    mDataTable1.hideColumn(parseInt(0)); mDataTable1.refreshView();
    mDataTable1.hideColumn(parseInt(1)); mDataTable1.refreshView();
    mDataTable1.hideColumn(parseInt(2)); mDataTable1.refreshView();
    mDataTable1.hideColumn(parseInt(11)); mDataTable1.refreshView();
     mDataTable1.hideColumn(parseInt(14)); mDataTable1.refreshView();
    //if (action == "insert" || flag=="2") {
        mDataTable1.hideColumn(parseInt(8)); mDataTable1.refreshView();
   // } else {
     //   mDataTable1.hideColumn(parseInt(7)); mDataTable1.refreshView();
   // }
    if (action == "insert") {
       // mDataTable1.hideColumn(parseInt(13)); mDataTable1.refreshView();
       
    } else {
      //  mDataTable1.showColumn(parseInt(13)); mDataTable1.refreshView();
      
    }
}
//值改变事件
var ChangeEvent1 = function (oArgs) {
    var f = oArgs.name;
    var v = oArgs.value;
    setValue1(f, v);
}
//f=字段名 v=值
var record;
var setValue1 = function (f, v) {
    var recordID = mDataTable1.getSelectedRows()[0];
    if (recordID != null && recordID.length != 1) {
        record = mDataTable1.getRecord(recordID);
        record._oData[f] = v;
        for (var i = 0; i < CrmProduct.length; i++) {
            if (CrmProduct[i].Caption == v) {
                record._oData["TypeId"] = CrmProduct[i].TypeId;
                record._oData["ProductId"] = CrmProduct[i].Productid;
                record._oData["PhraseText"] = CrmProduct[i].PhraseText;
                record._oData["Code"] = CrmProduct[i].Code;
                record._oData["Money"] = CrmProduct[i].Money;
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=TypeId]")[0]).val(CrmProduct[i].TypeId);
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=ProductId]")[0]).val(CrmProduct[i].Productid);
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=PhraseText]")[0]).val(CrmProduct[i].PhraseText);
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=Code]")[0]).val(CrmProduct[i].Code);
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=Money]")[0]).val(CrmProduct[i].Money);
            }
        }
        if (f == "Caption") {
            setTextValue();
        }
        if (f == "Amount") {
            if (isNaN(v)) { // || v == "0"
                alert("数量必须输入数字,且不能为0!");
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=Amount]")[0]).val("");
                record._oData["Amount"] = "";
            }
            $("#TotalRebate").val("");
            setTextValue();
        }
        if (f == "AccountReceivable") {
            if (isNaN(v)) {
                alert("应收金额必须输入数字!");
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=AccountReceivable]")[0]).val("");
                record._oData["AccountReceivable"] = "";
            }
            $("#TotalRebate").val("");
            setTextValueReceivable();
        }
        if (f == "ResignMoney") {
            if (isNaN(v)) {
                alert("已收金额必须输入数字!");
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=ResignMoney]")[0]).val("");
                record._oData["ResignMoney"] = "";
            }
            setTextValueResign();
        }
        if (f == "Rebate") {
            if (isNaN(v)) {
                alert("折扣率必须输入数字!");
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=Rebate]")[0]).val("");
                record._oData["Rebate"] = "";
            } else {
                if (v > 100) {
                    /*alert("折扣率不能超过100%!");
                    $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=Rebate]")[0]).val("");
                    record._oData["Rebate"] = "";*/
                }
            }
            $("#TotalRebate").val("");
            setTextValue();
        }
    } else {
        alert("请先选中当前行!");
    }
}
var setTextValueResign=function(){     
    var list = mDataTable1.getRecordSet()._records;
       // var cValue = 0;
        var sValue=0;
        for (var i = 0; i < list.length; i++) {
            if (list[i]._oData.ResignMoney != "") {          
            if(list[i]._oData.ResignMoney!=null)   { 
                var v = parseFloat(list[i]._oData.ResignMoney);
                sValue +=v;
             }
            }
        }
        $('#ShouldMoney').val(sValue.toFixed(2));
      //   $('#TotalMoney').val(cValue.toFixed(2));
}
var setTextValue = function () {
    var vM = record._oData["Money"];
    if (vM == "") {
        alert("请选择产品!");
        return;
    } else {
        var vMoney = record._oData["Money"];
        var vAmount = 0;
        var vRebate = 100;
        if (record._oData["Amount"] != null && record._oData["Amount"] != "null" && record._oData["Amount"] != "") {
            vAmount = parseFloat(record._oData["Amount"]);
        } else {
            vAmount = 1;
        }
        if (record._oData["Rebate"] != "") {
            vRebate = record._oData["Rebate"];
        }
        if (vAmount == "0") {
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val("0");
            record._oData["Rebate"] = "0";
        }
        var vRebateMoney = (vMoney * vAmount) - (vMoney * vAmount * (vRebate / 100));
        var vAccountReceivable = (vMoney * vAmount) - vRebateMoney;
        $($($(".yui-dt-selected")[0]).find("input[name=RebateMoney]")[0]).val(vRebateMoney.toFixed(2));
        //$($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=RebateMoney]")[0]).val(vRebateMoney.toFixed(2));
        record._oData["RebateMoney"] = "" + vRebateMoney.toFixed(2) + "";
        //$($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=AccountReceivable]")[0]).val(vAccountReceivable.toFixed(2));
        $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable]")[0]).val(vAccountReceivable.toFixed(2));
        record._oData["AccountReceivable"] = "" + vAccountReceivable.toFixed(2) + "";

        var list = mDataTable1.getRecordSet()._records;
        var cValue = 0;
        var sValue=0;
        for (var i = 0; i < list.length; i++) {
            if (list[i]._oData.AccountReceivable != "") {  
                var v = parseFloat(list[i]._oData.AccountReceivable);
                cValue += v;
                sValue+=  parseFloat(list[i]._oData.ResignMoney);;
            }
        }
        $('#TotalMoney').val(cValue.toFixed(2));
        $('#ShouldMoney').val(sValue.toFixed(2));
    }
}
var setTextValueReceivable = function () {
    var vM = record._oData["Money"];
    if (vM == "") {
        alert("请选择产品!");
        return;
    } else {
        var vMoney = record._oData["Money"];
        var vAmount = 0;
        var vRebate = 100;
        if (record._oData["Amount"] != "") {
            vAmount = record._oData["Amount"];
        } else {
            alert("请输入数量!");
            return;
        }
        if (record._oData["Rebate"] != "") {
            vRebate = record._oData["Rebate"];
        }
        if (record._oData["AccountReceivable"] == "" || record._oData["AccountReceivable"] == "0") {
            $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable]")[0]).val("0");
            //$($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=AccountReceivable]")[0]).val("");
            record._oData["AccountReceivable"] = "0";
            $($($(".yui-dt-selected")[0]).find("input[name=Amount]")[0]).val("0");
            record._oData["Amount"] = "0";
            $($($(".yui-dt-selected")[0]).find("input[name=RebateMoney]")[0]).val("0");
            record._oData["RebateMoney"] = "0";
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val("0");
            record._oData["Rebate"] = "0";
        } else {
            var AccountReceivable = record._oData["AccountReceivable"];
            vRebate = (AccountReceivable / (vMoney * vAmount)) * 100;
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val(vRebate.toFixed(2));
            //$($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=Rebate]")[0]).val(vRebate.toFixed(2)); 
            record._oData["Rebate"] = "" + vRebate.toFixed(2) + "";
            var vRebateMoney = (vMoney * vAmount) - (vMoney * vAmount * (vRebate / 100));
            $($($(".yui-dt-selected")[0]).find("input[name=RebateMoney]")[0]).val(vRebateMoney.toFixed(2));
            //$($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=RebateMoney]")[0]).val(vRebateMoney.toFixed(2));    ResignMoney       
            record._oData["RebateMoney"] = "" + vRebateMoney.toFixed(2) + "";
        }
        var list = mDataTable1.getRecordSet()._records;
        var cValue = 0;
       // var sValue=0;
        for (var i = 0; i < list.length; i++) {
            if (list[i]._oData.AccountReceivable != "") {              
                var v = parseFloat(list[i]._oData.AccountReceivable);
                cValue += v;
               // sValue += parseFloat(list[i]._oData.ResignMoney);
            }
        }
       // $('#ShouldMoney').val(sValue.toFixed(2));
         $('#TotalMoney').val(cValue.toFixed(2));
    }
}
//设置值1
var GetFormValue = function () {
    for (var i = 0; i < CrmOrderProdcut.length; i++) {
        SetFormValue(CrmOrderProdcut);
    }
}
var SetFormValue = function (obj) {
    var arr = eval(obj);
    myDataSource1.liveData = arr;
    mDataTable1.getDataSource().sendRequest(null, { success: mDataTable1.onDataReturnInitializeTable }, mDataTable1);
}
//新增行
var handleAdd = function () {
    mDataTable1.set("sortedBy", null);
    index = mDataTable1.getRecordSet()._records.length;
    var entity = [{ ID: "", Code: "", TypeId: "", Caption: "", Money: "", Rebate: ""
                    , Amount: "", UnitId: "", RebateMoney: "", AccountReceivable: ""
                  
    }];
    mDataTable1.addRows(entity, index);
}
//产品删除行
var handleDelete = function () {
    var recordID = mDataTable1.getSelectedRows()[0];
    if (recordID != null && recordID.length != 1) {
        if (mDataTable1.getRecordSet()._records.length == 1) {
            alert("最后一行不能删除!");
            return;
        } else {
            var OrderId = $('#ID').val();
            record = mDataTable1.getRecord(recordID);
            var vid = record.getData("ID");
            if (flag == "0" || vid == "" || vid == "00000000-0000-0000-0000-000000000000") {
                mDataTable1.deleteRow(recordID);
                LoadAccountReceivable();
            } else {
                if (confirm("您确定删除该行吗?")) {
                    var SaveUrl = Url + "?r=" + Math.random() + "&action=delete&entity=CrmOrderProduct&json=&oid=" + OrderId + "&id=" + vid;
                    YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
                        success: function (res) {
                            try {
                                var str = res.responseText;
                                if (str == "1") {
                                    alert("删除成功!");
                                    mDataTable1.deleteRow(recordID);
                                    LoadAccountReceivable();
                                }
                                else {
                                    alert(str + "\n" + "数据删除失败!");
                                    return;
                                }
                            }
                            catch (e) {
                            }
                            finally {
                            }
                        },
                        failure: function (error) {
                            alert("数据错误：" + error.statusText);
                        }
                    }, null);
                }
            }
        }
    } else {
        alert("请选中一行后删除！");
    }
}
function LoadAccountReceivable() {
    var list = mDataTable1.getRecordSet()._records;
    var cValue = 0;
    var sValue=0;
    for (var i = 0; i < list.length; i++) {
        if (list[i]._oData.AccountReceivable != "") {
            var v = Number(list[i]._oData.AccountReceivable);
            cValue += v;
            sValue += parseFloat(list[i]._oData.ResignMoney);
        }
    }
    $('#ShouldMoney').val(sValue.toFixed(2));
    $('#TotalMoney').val(cValue);
}
//刷新父窗体数据
function RefreshDataParent() {
    if (parent.NeedRefreshPage != null) {
        if (typeof (parent.NeedRefreshPage.LoadData) == "function") {
            parent.NeedRefreshPage.RefreshData();
        }
    }
}
//总折扣率
function TotalRebateChange(value) {
    if (value != "") {
        var elist = [];
        var list = mDataTable1.getRecordSet()._records;
        var TotalRebate = $("#TotalRebate").val();
        for (var i = 0; i < list.length; i++) {
            if (list[i]._oData.ID == "" || list[i]._oData.ID == null) {
                list[i]._oData.ID = "00000000-0000-0000-0000-000000000000";
            }
            if (list[i]._oData.Code == "" || list[i]._oData.Code == "00" || list[i]._oData.Code == null) {
                alert("第" + (i + 1) + "行 产品名称不能为空!");
                $('#TotalRebate').val("");
                return;
            }
            if (list[i]._oData.UnitId == "" || list[i]._oData.UnitId == "00" || list[i]._oData.UnitId == null) {
                alert("第" + (i + 1) + "行 计量单位不能为空!");
                $('#TotalRebate').val("");
                return;
            }
            if (list[i]._oData.Amount == "" || list[i]._oData.Amount == null) {
                alert("第" + (i + 1) + "行 数量不能为空且不能为0!");
                $('#TotalRebate').val("");
                return;
            }
            if (list[i]._oData.Rebate == "" || list[i]._oData.Rebate == null) {
                //alert("第" + (i + 1) + "行 折扣率不能为空!");
                //return;
                list[i]._oData.Rebate = "100";
            }
            if (list[i]._oData.RebateMoney == "" || list[i]._oData.RebateMoney == null) {
                alert("第" + (i + 1) + "行 折扣金额不能为空!");
                $('#TotalRebate').val("");
                return;
            }
            if (list[i]._oData.AccountReceivable == "" || list[i]._oData.AccountReceivable == null) {
                alert("第" + (i + 1) + "行 应该收金额不能为空!");
                $('#TotalRebate').val("");
                return;
            }
            if (TotalRebate != "") {  //总折扣率
                var Rebate = list[i]._oData.Rebate;
                var Money = list[i]._oData.Money;
                var Amount = list[i]._oData.Amount;
                var vAccount = Money * Amount * (TotalRebate / 100);
                var vRebate = (Money * Amount) - vAccount;
                //数量
                list[i]._oData.Amount = Amount;
                //折扣率
                //var v = (Rebate * TotalRebate / 100);
                list[i]._oData.Rebate = TotalRebate;
                //折扣金额
                list[i]._oData.RebateMoney = vRebate.toFixed(2);
                //应收金额
                list[i]._oData.AccountReceivable = vAccount.toFixed(2);
            }
            elist.push(list[i]._oData);
            elist[i].OrderID = $('#ID').val();
        }
        if (confirm("您确定总折扣率为 " + value + "%")) {
            SetFormValue(elist);
            LoadAccountReceivable();
            return;
        } else {
            $('#TotalRebate').val("");
        }
    }
}


  $('#ddlProductPack').change(function () {         
     var vValue = $(this).children('option:selected').val();
            if (vValue != "") {
                LoadPackDetail(vValue);
            } else {
                SetFormValue("");
                $('#TotalMoney').val("");
                handleAdd();
            }
            $('#TotalRebate').val("");
            $('#ShouldMoney').val("");
 });
   //加载产品包详细信息
var LoadPackDetail = function (objValue) {
    var vCId = "PackID='" + objValue + "'";
    YAHOO.util.Connect.asyncRequest('GET', "../../Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=V_CrmPackDetail&customCondition=" + vCId + "", //条件 
        {success: function (res) {
            try {
                var str = res.responseText;
                var obj = eval(str);
                var total = 0;
                for (var i = 0; i < obj.length; i++) {
                    SetFormValue(obj);
                    var v = Number(obj[i].AccountReceivable);
                    total += v;
                }
                $('#TotalMoney').val(total.toFixed(2));
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
    });
}
    //重置
    var clearForm = function () {
        location.reload(false)
    };
    function setValue() {
        instance[0].ID = $("#ID").val();
        instance[0].CourseLayoutID = StrProductId;
        instance[0].CustomerID = $("#CustomId").val();
        instance[0].ProductPack = $("#ddlProductPack").val();
        instance[0].TotalMoney = $('#TotalMoney').val();
        instance[0].ResignMoney = $('#ShouldMoney').val();
        instance[0].TotalRebate = $('#TotalRebate').val();
        instance[0].PayType = $('#ddlPayType').val();
        instance[0].POSNum = $('#POSNum').val();
        instance[0].IsInvoice = $('#ddlIsInvoice').val();
        instance[0].InvoiceNum = $('#InvoiceNum').val();
        instance[0].PactNum = $('#PactNum').val();
        instance[0].ReceiptNum = $('#ReceiptNum').val();
        instance[0].Explain = $('#Explain').val();
        instance[0].AddUser = $("#AddUser").val();
        instance[0].AddTime = $("#AddTime").val();
        instance[0].NegotiateTeachID = $("#Memember").val();
        instance[0].CrmDeliverMajorID=$("#CrmDeliverMajorID").val();
    }
    //重置
    var clearForm = function () {
        location.reload(false)
    };
     //应收金额
       var changePay = function () {
           if ($('#ProductPrice').val() == ""&&$('#Amount').val()!="") {
               alert("请先选择产品");   
               $('#Amount').val("");
               $("#ddlProductName").focus();   $("#ddlProductPack").focus();
               return;
           }
           $("#AccountReceivable").val($('#Amount').val() * $('#ProductPrice').val());
       }
      //产品类型
      var packChange=function(){   var chkTemp=document.getElementsByName("a");
        if(chkTemp[0].checked)       {
            document.getElementById("ddlProductName").style.display="";
            document.getElementById("ddlProductPack").style.display="none";
        }else{
           document.getElementById("ddlProductName").style.display="none";
            document.getElementById("ddlProductPack").style.display="";
        }
      }
    //客户端验证
    var checkData = function () {   
        if ($("#txtCustomId").val() == "") {
            alert("客户必须选择");
            $("#txtCustomId").focus();
            return false;
        }

        return true;
    }
    //保存
    var Save = function () {
        if (checkData()) {
            setValue();
             
        var list = mDataTable1.getRecordSet()._records;
        var elist = [];
        instance[0].ProduectList = "";
        var TotalRebate = $("#TotalRebate").val();
        for (var i = 0; i < list.length; i++) {
            if (list[i]._oData.ID == "" || list[i]._oData.ID == null) {
                list[i]._oData.ID = "00000000-0000-0000-0000-000000000000";
            }
            if (list[i]._oData.Code == "" || list[i]._oData.Code == "00" || list[i]._oData.Code == null) {
                alert("第" + (i + 1) + "行 产品名称不能为空!");
                return;
            }
            if (list[i]._oData.UnitId == "" || list[i]._oData.UnitId == "00" || list[i]._oData.UnitId == null) {
                alert("第" + (i + 1) + "行 计量单位不能为空!");
                return;
            }
            if (list[i]._oData.Amount == "" || list[i]._oData.Amount == null) {
                alert("第" + (i + 1) + "行 数量不能为空且不能为0!");
                return;
            }
            if (list[i]._oData.Rebate == "" || list[i]._oData.Rebate == null) {
                //alert("第" + (i + 1) + "行 折扣率不能为空!");
                //return;
                list[i]._oData.Rebate = "100";
            }
            if (list[i]._oData.RebateMoney == "" || list[i]._oData.RebateMoney == null) {
                alert("第" + (i + 1) + "行 折扣金额不能为空!");
                return;
            }
            if (list[i]._oData.AccountReceivable == "" || list[i]._oData.AccountReceivable == null) {
                alert("第" + (i + 1) + "行 应该收金额不能为空!");
                return;
            }
            elist.push(list[i]._oData);
            elist[i].OrderID = $('#ID').val();
        }
        for (var j = 0; j < elist.length; j++) {
        var rmTemp=0;
        if(elist[j].ResignMoney!=null&&elist[j].ResignMoney!=""){
               rmTemp=elist[j].ResignMoney;
        }
            instance[0].ProduectList += "@" + elist[j].ID + "︾" + elist[j].OrderID + "︾" + elist[j].ProductId + "︾" +
                                            elist[j].Rebate + "︾" + elist[j].Amount + "︾" + elist[j].UnitId + "︾" +
                                            elist[j].RebateMoney + "︾" + elist[j].AccountReceivable + "︾"+ rmTemp + "︾";
        }           
        if (instance[0].TotalMoney == "" || instance[0].TotalMoney == null) {
            alert("总金额不能为空!");
            $('#TotalMoney').focus();
            return;
        }
        var json = $.toJSON(instance[0]).replace(/'/g, "[B]");
        $("#jsonDataContent").val(json);                       
        if (confirm("您确定保存当前现场销售订单信息?")) {
            trySave();
        }  
       }  
    }
    var trySave = function () {  
        var formObject = document.getElementById('form2');
        YAHOO.util.Connect.setForm(formObject);     
        var cObj = YAHOO.util.Connect.asyncRequest('POST', Url + "?flag=1&action=insert&entity=CrmLiveOrDerManager", callback);
}
    var WinClose = function () {
        window.parent.$("#tabs").tabs('close', '新增现场销售');
        window.parent.$("#tabs").tabs('close', '修改现场销售');
        parent.NeedRefreshPage.RefreshData();
    };

   var responseSuccess = function (res) {
        try {                 
            var str = res.responseText;
            if (str == "1") {
                if (document.getElementById("onceMore").checked) {
                    alert("数据保存成功");
                    clearForm();
                } else {
                    alert("数据保存成功");
                    //                        if ($("#onceMore").val()) {

                    //                        }                              
                    WinClose();
                }
            }
            else {
                alert(str + "\n" + "数据保存失败!");
            }
        }
        catch (e) {
        }
        finally {
        }
    }

    var responseFailure = function (error) {
        alert("数据错误：" + error.statusText);
    }

    var callback = {
        success: responseSuccess,
        failure: responseFailure
    };
    $(document).ready(function () {
        $('#Birthday').cld();

    });  
</script>
<script src="../../Scripts/appjs/model.<% =EntityName %>.js" type="text/javascript"
    language="javascript"></script>
</html>
